package com.lxp.common.task;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lxp.service.MqttGateway;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.RoundingMode;

/**
 * 获取电表数据定时器
 */
@Slf4j
@Component
@EnableScheduling// 1.开启定时任务
@EnableAsync// 2.开启多线程
public class DataTask implements SchedulingConfigurer {
    @Resource
    private MqttGateway mqttGateway;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        // 任务逻辑,使用了lombok表达式
        taskRegistrar.addTriggerTask(this::sendMqttData, triggerContext -> {
            // 任务触发，可修改任务的执行周期
            CronTrigger trigger = new CronTrigger("* 0/1 * * * ?");
            return trigger.nextExecutionTime(triggerContext);
        });
    }

    public void sendMqttData() {
        String topic = "xky/up/sgw/002/1";
        double aDouble = RandomUtil.randomDouble(0.0, 500.0, 2, RoundingMode.DOWN);
        double v = RandomUtil.randomDouble(0.0, 100.0, 2, RoundingMode.DOWN);
        double v1 = RandomUtil.randomDouble(0.0, 100.0, 2, RoundingMode.DOWN);

        log.info("返回的{},湿度:{}", aDouble, v);
        JSONObject json1 = JSONUtil.createObj().set("method", aDouble).set("shidu", v).set("wendu",v1);
        mqttGateway.sendToMqtt(json1.toString(), topic);
    }
}
